package org.jflame.commons.json.fastjson;

import org.jflame.commons.model.pair.IIntKeyPair;

import java.io.IOException;
import java.lang.reflect.Type;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class IntKeyPairEnumCustomized {

    /**
     * IntKeyPair自定义序列化,只输出key值
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairUsingKeySerializer implements ObjectSerializer {

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
                throws IOException {
            SerializeWriter out = serializer.out;
            if (object == null) {
                out.writeNull();
            } else {
                out.writeInt(((IIntKeyPair) object).getKey());
            }
        }

    }

    /**
     * 实现了IntKeyPair接口的枚举类的自定义反序列化. 通过key值生成相应枚举类
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairEnumDeserializer implements ObjectDeserializer {

        @SuppressWarnings("unchecked")
        @Override
        public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            Integer intVal = parser.parseObject(Integer.class);
            Class<T> enumClazz = (Class<T>) type;
            if (IIntKeyPair.class.isAssignableFrom(enumClazz)) {
                T[] enums = enumClazz.getEnumConstants();
                if (enums == null) {
                    throw new JSONException("Type mismacth, '" + enumClazz.getSimpleName() + "' not an enum class");
                }
                for (T e : enums) {
                    IIntKeyPair pair = (IIntKeyPair) e;
                    if (pair.getKey()
                            .equals(intVal)) {
                        return e;
                    }
                }
                return null;
            } else {
                throw new JSONException("Type mismacth," + type.getTypeName() + " not implement interface IIntKeyPair");
            }
        }

        @Override
        public int getFastMatchToken() {
            return JSONToken.LITERAL_INT;
        }
    }
}
